package com.zhongshengnetwork.rightbe.login;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
//import android.support.v4.view.GestureDetectorCompat;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.core.view.GestureDetectorCompat;

import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.DeviceUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.MD5;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.loading.KyLoadingBuilder;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.dbmodel.LogindbModel;
import com.zhongshengnetwork.rightbe.dbservice.LogindbService;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.my.activity.MyInfoActivity;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class RegisterActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener{
    private GestureDetectorCompat mDetector;
    private boolean flag=false;//标记edittext不会死循环
    private TopBarView topbar;
    private EditText accountText;
    private EditText codeText;
    private Button codeBt;
    private EditText passwordText;
    private EditText nicknameText;
    private Button finishBt;
    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private Handler mHandler = null;
    private final static int TimeOut = 91;
    private int timeCount = 0;
    private static int delay = 1000;  //1s
    private static int period = 1000;  //1s
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mDetector = new GestureDetectorCompat(this, new MyGestureListener());
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        accountText = (EditText) findViewById(R.id.register_account);
        codeText = (EditText) findViewById(R.id.register_codetext);
        codeBt = (Button) findViewById(R.id.register_codebt);
        passwordText = (EditText) findViewById(R.id.register_password);
        nicknameText = (EditText) findViewById(R.id.register_nickname);
        finishBt = (Button) findViewById(R.id.register_finishbt);

        LinearLayout register = (LinearLayout) findViewById(R.id.register);
        register.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());

        EditText register_account = (EditText) findViewById(R.id.register_account);
        register_account.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        register_account.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        register_account.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

        Button register_codebt = (Button) findViewById(R.id.register_codebt);
        register_codebt.setBackgroundResource(AppThemeUtils.getInstance().getComsytleBg());

        EditText register_codetext = (EditText) findViewById(R.id.register_codetext);
        register_codetext.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        register_codetext.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        register_codetext.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

        EditText register_nickname = (EditText) findViewById(R.id.register_nickname);
        register_nickname.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        register_nickname.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        register_nickname.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

        EditText register_password = (EditText) findViewById(R.id.register_password);
        register_password.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        register_password.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        register_password.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

        Button register_finishbt = (Button) findViewById(R.id.register_finishbt);
        register_finishbt.setBackgroundResource(AppThemeUtils.getInstance().getComsytleBg());

        // 定义Handler
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg == null){
                    return;
                }
                //handler处理消息
                if(msg.what>0){
                    codeBt.setText(msg.what+"秒");
                }else{
                    //在handler里可以更改UI组件
                    stopTimer();
                    codeBt.setText("获取验证码");
                }
            }
        };
    }

    private void startTimer(){
        if (mTimer == null) {
            mTimer = new Timer();
        }

        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    if (timeCount > 0){
                        timeCount--;
                    }
                    sendMessage(timeCount);
                }
            };
        }

        if(mTimer != null && mTimerTask != null ){
            if (timeCount == 0){
                timeCount = TimeOut;
                mTimer.schedule(mTimerTask, delay, period);
            }
        }

    }

    private void stopTimer(){
        if (mTimer != null) {
            timeCount = 0;
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        codeBt.setClickable(true);
        timeCount = 0;
    }

    public void sendMessage(int id){
        if (mHandler != null) {
            Message message = Message.obtain(mHandler, id);
            mHandler.sendMessage(message);
        }
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    //获取验证码
    private void getCode(){
        if (accountText.getText().toString().trim().length() < 11){
            ToastUtil.show(RegisterActivity.this,"请输入11位手机号");
            return;
        }
        if (timeCount > 0){
            return;
        }
        codeBt.setClickable(false);
        codeBt.setText("获取中...");
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.accountKey, accountText.getText().toString());
        map.put(APIKey.typeKey, Constant.registerCode+"");
        HttpsUtils.getCodeDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    startTimer();
                }else {
                    ToastUtil.show(RegisterActivity.this,commonModel.getMsg());
                    stopTimer();
                    codeBt.setText("获取验证码");
                    codeBt.setClickable(true);
                    return;
                }
            }

            @Override
            public void onError(String msg) {
                stopTimer();
                codeBt.setText("获取验证码");
                codeBt.setClickable(true);
            }
        });
    }

    //注册
    private void register(){
        finishBt.setClickable(false);
        KyLoadingBuilder dialog = new KyLoadingBuilder(RegisterActivity.this);
        dialog.setIcon(R.drawable.loading04);
        dialog.setText("正在注册...");
        dialog.setOutsideTouchable(false);//点击空白区域是否关闭
        dialog.setBackTouchable(true);//按返回键是否关闭
        dialog.show();
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.accountKey,accountText.getText().toString());
        map.put(APIKey.randcodeKey,codeText.getText().toString());
        map.put(APIKey.passwordKey,MD5.GetMD5Code(passwordText.getText().toString()));
        map.put(APIKey.nicknameKey,nicknameText.getText().toString());
        map.put(APIKey.sexKey,"0");
        map.put("mobileid", DeviceUtils.getDeviceID());
        HttpsUtils.registerDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    stopTimer();
                    dialog.dismiss();
                    try {
                        JSONObject jsonObject = CommonUtils.stringToJson(data);
                        LogindbModel model = GsonTools.getLoginModel(jsonObject.getString(APIKey.dataKey), MD5.GetMD5Code(passwordText.getText().toString()));
                        System.out.print("~rctoken~:"+model.getRctoken()+"\n");
                        CustomApplication.loginModel.setRctoken(model.getRctoken());
                        CustomApplication.loginModel.setToken(model.getToken());
                        CustomApplication.loginModel.setExpires(model.getExpires());
                        CustomApplication.loginModel.setUid(model.getUid());
                        CustomApplication.loginModel.setHeader(model.getHeader());
                        CustomApplication.loginModel.setThumbheader(model.getThumbheader());
                        CustomApplication.loginModel.setBackground(model.getBackground());
                        CustomApplication.loginModel.setNickname(model.getNickname());
                        CustomApplication.loginModel.setSex(model.getSex());
                        CustomApplication.loginModel.setSignature(model.getSignature());
                        CustomApplication.loginModel.setLocation(model.getLocation());
                        CustomApplication.loginModel.setUserauth(model.getUserauth());
                        CustomApplication.loginModel.setPayauth(model.getPayauth());
                        CustomApplication.loginModel.setWeiJuId(model.getWeiJuId());
                        CustomApplication.loginModel.setMobile(model.getMobile());
                        CustomApplication.loginModel.setNeed(model.getNeed());
                        LogindbService.deleteLoginModel();
                        LogindbService.saveOrUpdateLogindbMode(model);

                        setResult(RESULT_OK);
                        ToastUtil.show(RegisterActivity.this,"注册成功");
                        finish();
                    }catch (Exception e){
                        finishBt.setClickable(true);
                        ToastUtil.show(RegisterActivity.this,"注册不成功呀~");
                    }
                }else {
                    stopTimer();
                    codeBt.setText("获取验证码");
                    codeBt.setClickable(true);
                    dialog.dismiss();
                    finishBt.setClickable(true);
                    ToastUtil.show(RegisterActivity.this,commonModel.getMsg());
                }
            }

            @Override
            public void onError(String msg) {
                dialog.dismiss();
                finishBt.setClickable(true);
                ToastUtil.show(RegisterActivity.this,"注册失败");
            }
        });
    }

    /**
     * @param v
     */
    public void onClickCode(View v) {
        hintKeyBoard();
        getCode();
    }

    public void onClickFinish(View v) {
        hintKeyBoard();
        if (accountText.getText().toString().trim().length() < 11){
            ToastUtil.show(RegisterActivity.this,"请输入11位手机号");
            return;
        }
        if (codeText.getText().toString().trim().length() < 6){
            ToastUtil.show(RegisterActivity.this,"请输入6位验证码");
            return;
        }

        if (passwordText.getText().toString().trim().length() < 6){
            ToastUtil.show(RegisterActivity.this,"请输入6~20位数字或字母密码");
            return;
        }

        if (nicknameText.getText().toString().trim().length() <= 0){
            ToastUtil.show(RegisterActivity.this,"请输入昵称");
            return;
        }
        //stopTimer();
        register();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        hintKeyBoard();
        stopTimer();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    /**
     * 屏幕事件
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event){
        this.mDetector.onTouchEvent(event);
        return super.onTouchEvent(event);
    }

    class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
        /**
         * 屏幕操作事件
         */
        private static final String DEBUG_TAG = "Gestures";
        @Override
        public boolean onDown(MotionEvent event) {
            Log.d(DEBUG_TAG,"onDown: " + event.toString());
            /*
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            boolean isOpen=imm.isActive();//isOpen若返回true，则表示输入法打开
            if(isOpen == true){
                //隐藏键盘
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
            */
            hintKeyBoard();
            return true;
        }

        @Override
        public boolean onFling(MotionEvent event1, MotionEvent event2,
                               float velocityX, float velocityY) {
            Log.d(DEBUG_TAG, "onFling: " + event1.toString()+event2.toString());
            return true;
        }
    }
}
